package com.vieewer.btdemo.view.main

import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.content.pm.PackageManager
import android.media.AudioManager
import android.os.Bundle
import android.os.Handler
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.util.Log
import android.view.KeyEvent
import android.view.WindowManager
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONException
import com.lindroid.androidutilskt.extension.getSp
import com.lindroid.androidutilskt.extension.putSp
import com.lindroid.androidutilskt.extension.shortToast
import com.lindroid.androidutilskt.extension.systemBrightness
import com.lindroid.androidutilskt.statics.AppManager
import com.vieewer.btdemo.R
import com.vieewer.btdemo.base.BaseActivity
import com.vieewer.btdemo.view.info.SugonGlassesInfoManager
import com.vieewer.btdemo.view.vpanim.ZoomOutPageTransformer
import com.vieewer.btdemo.adapter.HomePagerAdapter
import com.vieewer.btdemo.app.App
import com.vieewer.btdemo.bean.*
import com.vieewer.btdemo.common.Constants
import com.vieewer.btdemo.t
import com.vieewer.btdemo.utils.*
import com.vieewer.btdemo.view.brightness.BrightnessActivity
import com.vieewer.btdemo.view.brightness.SugonSettingsActivity
import com.vieewer.btdemo.view.brightness.VolumeActivity
import com.vieewer.btdemo.view.compass.CompassManager
import com.vieewer.btdemo.view.gdmap.preview.GdMapPreviewActivity
import com.vieewer.btdemo.view.main.fragment.MenuFragment
import com.vieewer.btdemo.view.main.fragment.SysInfoFragment
import com.vieewer.btdemo.view.map.MapGuideActivity
import com.vieewer.btdemo.view.microsoft.translate.TranslateLanguageActivity
import com.vieewer.btdemo.view.mycamera.SurfaceCameraActivity
import com.vieewer.btdemo.view.net.connect.ConnectWifTools
import com.vieewer.btdemo.view.notification.DialogActivity
import com.vieewer.btdemo.view.phonecall.BluetoothCallActivity
import com.vieewer.btdemo.view.test.TestMiCompassActivity
import com.vieewer.btdemo.view.travel.TravelActivity
import com.vieewer.btdemo.view.wifi.TransferPhotosManager
import com.vieewer.btdemo.wifimain.MainActivity
import com.vieewer.btdemo.wifimain.RadioActivity
import com.vieewer.btdemo.wifimain.VideoActivity
import com.vieewer.classicbt.BleManager
import com.vieewer.classicbt.BluetoothPermissionHandler
import com.vieewer.classicbt.CLog
import com.vieewer.classicbt.Connect
import com.vieewer.classicbt.listener.BluetoothPermissionCallBack
import com.vieewer.classicbt.listener.ConnectResultlistner
import com.vieewer.classicbt.listener.TransferProgressListener
import kotlinx.android.synthetic.main.activity_gallery.*
import org.greenrobot.eventbus.EventBus
import kotlin.collections.ArrayList


class HomeGuideActivity : BaseActivity(), BluetoothPermissionCallBack {

    private var mViewPagerAdapter: HomePagerAdapter? = null
    /*蓝牙通信相关*/
    private lateinit var list: ArrayList<BluetoothDevice>
    var connect: Connect? = null
    private val permissionCallBack = BluetoothPermissionHandler(this, this)
    private var mAudioManager: AudioManager? = null
    //全局toast避免多次弹出
    private var mToast: Toast? = null
    var mCurPos = 0

    var isInited = false
    var isBleConnected = false

    var mSysFragment: Fragment? = null

    var mDelayMills: Long = 60 * 1000


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gallery)
        initScreenSleep()
        initViewpager()
        initUI()
    }

    private fun initUI() {

        Handler().postDelayed(
            {
                if (mCurPos == 0) {
                    setBleConnectStatusUI()
                    setWifiConnectStatusUI()
                }
            }, 2 * 1000
        )


        test_txt.setOnClickListener {
            //todo
            startActivity(Intent(this, RadioActivity::class.java))
        }


    }


    private fun initScreenSleep() {
        window.addFlags(
            WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
                    WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
        )
        var sleepTime = getSp(Constants.SP_KEY_COMMON_SLEEP_SCREEN_TIME, 15)
        ScreenSleepUtil.setScreenSleepTime(sleepTime * 1000, this@HomeGuideActivity)
    }


    override fun onResume() {
        super.onResume()
        //防止页面卡顿，防止页面重复初始化，这里延迟初始化
        if (!isInited) {
            initCommons()
//            initBluetooth()
            initTravelCompass()
            isInited = true
            putSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, false)
        }

        if (!getSp(Constants.SP_KEY_SHOW_MAP_GUIDE_AGAIN_INSTANTLY_TAG, false)) {
            mDelayMills = 60 * 1000
            putSp(Constants.SP_KEY_SHOW_MAP_GUIDE_AGAIN_INSTANTLY_TAG, true)
        } else {
            mDelayMills = 1 * 1000
        }


        //导航出来切换功能，等待一分钟，重新显示导航信息
        if (getSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, false)) {

            Handler().postDelayed({
                //用户没有切换功能
                if (AppManager.currentActivity()!!.localClassName == "view.main.HomeGuideActivity") {
                    putSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, false)
                    Log.i(
                        "yjj",
                        "not switch show map~~~" + AppManager.currentActivity()!!.localClassName + ", mDelayMills >>>" + mDelayMills
                    )
                } else { //用户切换功能了
                    putSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, true)
                    Log.i(
                        "yjj",
                        "has switch ~~~" + AppManager.currentActivity()!!.localClassName + ", mDelayMills >>>" + mDelayMills
                    )
                }

            }, mDelayMills)

        }

    }


    private fun quitOutMap() {
        putSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, false)
        sendToFinishMapGuide()
    }

    private fun sendToFinishMapGuide() {
        val data = SwitchMsgBean()
        data.type = "finishMap"
        val dataStr = JSON.toJSONString(data)
        LogUtil.e("yjj", "sendSuccessToPhone finish map guide ~~~")
        CommunicateToPhoneHelper.instance.write(dataStr)
    }


    private fun initTravelCompass() {
        CompassManager.getNewInstance().init(this)
    }

    private fun initCommons() {
        if (SugonGlassesInfoManager.instance != null) {
            SugonGlassesInfoManager.instance.initManager(this)
        }
        PermissionUtil.requestPermissions(this)
        PermissionUtil.checkPermission(this)
        TransferPhotosManager.getNewInstance().init(this@HomeGuideActivity)
        ConnectWifTools.getNewInstance().init(this@HomeGuideActivity)
    }


    private fun initBluetooth() {

        mToast = Toast.makeText(this, "received message", Toast.LENGTH_SHORT)
        mAudioManager = getSystemService(AUDIO_SERVICE) as AudioManager

        //recyclerview.layoutManager = LinearLayoutManager(this)
        list = ArrayList()
        //recyclerview.adapter = MyAdapter(this@HomeGuideActivity, list)
        permissionCallBack.start()

        //t("register server success.you can connnect device now.")
        registerServer()


        BleManager.getInstance().enableDiscoverable(300)


        test_txt.setOnClickListener {
            //todo
            //BleManager.getInstance().enableDiscoverable(300)
            startActivity(Intent(this, RadioActivity::class.java))
        }

        txt_goto_travel.setOnClickListener {
            //startActivity(Intent(this, PhoneCallActivity::class.java))
            //startActivity(Intent(this, MapGuideActivity::class.java))

            startActivity(Intent(this, TravelActivity::class.java))
        }


    }


    override fun onBlueToothEnabled() {
        BleManager.getInstance().init(application)
        BleManager.getInstance().setForegroundService(true)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        permissionCallBack.onActivityResult(requestCode, resultCode, data)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        permissionCallBack.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }


    fun registerServer() {
        BleManager.getInstance().registerServerConnection(object : ConnectResultlistner {

            override fun disconnected() {
                t("bluetooth has disconnected ~~~")
                BleManager.getInstance().destory()
                registerServer()
                isBleConnected = false
                setBleConnectStatusUI()
            }

            override fun connectSuccess(connect: Connect?) {

                this@HomeGuideActivity.connect = connect
                CommunicateToPhoneHelper.instance.connect = connect
                shortToast("server connect Success")
                isBleConnected = true
                setBleConnectStatusUI()

                Handler().postDelayed({
                    sendSugonInfotoPhone()
                }, 5 * 1000)

                read()

            }

            override fun connectFailed(e: Exception?) {
                Log.i("yjj", "ble connectFailed ")
                isBleConnected = false
                setBleConnectStatusUI()
            }

        })
    }

    private fun setBleConnectStatusUI() {
        //var bleStatus = if (isBleConnected) "蓝牙已连接" else "蓝牙断开"
        (mSysFragment as SysInfoFragment).refreshBleStatus(isBleConnected)
    }

    private fun setWifiConnectStatusUI() {
        var isWifiConnected = NetAssistUtil.isWifiConnected(this) || NetAssistUtil.isMobileConnected(this)
                || NetAssistUtil.isNetWorkConnected(this)
        //var wifiStatus = if (isWifiConnected) "Wifi已连接" else "Wifi断开"
        (mSysFragment as SysInfoFragment).refreshWifiStatus(isWifiConnected)
    }


    private fun sendSugonInfotoPhone() {

        val data = SugonInfoBean()
        data.type = "blueTooth_success"
        data.bluetoothName = SugonInfoUtils.getBluetoothName()
        data.connectWifiName = SugonInfoUtils.getConnectWifiSsid(this)
        data.diskValue = SugonInfoUtils.getDiskValue()
        data.totalValue = SugonInfoUtils.getDiskTotal()
        val dataStr = JSON.toJSONString(data)
        LogUtil.e("yjj", "sendSugonInfotoPhone$dataStr")
        CommunicateToPhoneHelper.instance.write(dataStr)

    }


    fun read() {
//        val a:Int= -0x146f1470
//        val buffer=ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(a)
//        val b:Byte= 0x03
//        val buffer2=ByteBuffer.allocate(1).order(ByteOrder.LITTLE_ENDIAN).put(b)
        /*     connect?.setReadPacketVerifyListener(object : PacketDefineListener {
                 override fun getPacketStart(): ByteArray {
                     return start

                 }

                 override fun getPacketEnd(): ByteArray {
                     return end

                 }
             })*/
        connect?.read(object : TransferProgressListener {

            override fun transferSuccess(bytes: ByteArray?) {
                //t("received message")
                mToast!!.show()
                bytes?.let { it1 ->
                    //tvReceive.text = String(it1)
                }

                operateResult(bytes)

            }

            override fun transferFailed(msg: Exception) {
                msg.printStackTrace()
//                msg.message?.run {
//                    t(this)
//                }

            }

            override fun transfering(progress: Int) {
                CLog.e("read progress:$progress")
            }
        })
    }


    override fun permissionFailed() {

    }


    private fun operateResult(bytes: ByteArray?) {

        var result = String(bytes!!)

        LogUtil.e("HomeGuideActivity", "read string bytes ?>>>$result")
        //todo try catch exception
        try {
            var jsonObject = JSON.parseObject(result)

            when (jsonObject["type"]) {

                Constants.COMMON_TYPE_STS_SETTING -> {

                    var bean = JSON.parseObject(result, SystemSettingsBean::class.java)
                    if (bean != null) {
                        if (bean.sys_type == SystemSettingsBean.SYS_TYPE_BRIGHTNESS) {
                            systemBrightness = bean.progress
                        } else if (bean.sys_type == SystemSettingsBean.SYS_TYPE_VOLUME) {
                            mAudioManager!!.setStreamVolume(
                                AudioManager.STREAM_MUSIC,
                                bean.progress,
                                AudioManager.FLAG_SHOW_UI
                            )
                        }

                        CLog.e("system progress >>>" + bean.progress)
                    }

                }

                Constants.COMMON_TYPE_MAP -> {

                    Log.i("yjj", "map view 111")

                    if (!getSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, false)) {

                        Log.i("yjj", "map view 222")
                        var bean = JSON.parseObject(result, MapDataBean::class.java)
                        if (bean != null) {

                            if (AppManager.currentActivity()!!.localClassName == "view.gdmap.preview.GdMapPreviewActivity") {
                                AppManager.currentActivity()!!.finish()
                            }

                            if (AppManager.currentActivity()!!.localClassName == "view.map.MapGuideActivity") {
                                Log.i("yjj", "refresh map view" + AppManager.currentActivity()!!.localClassName)
                                MapGuideActivity.refreshView(bean)
                            } else {
                                Log.i("yjj", "goto map view")
                                var intent = Intent(AppManager.currentActivity(), MapGuideActivity::class.java)
                                intent.putExtra("data", bean)
                                startActivity(intent)
                            }

                        }
                    }

                }


                //地图红绿灯信息
                Constants.COMMON_TYPE_GD_MAP_LANEINFO -> {
                    if (!getSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, false)) {
                        var bean = JSON.parseObject(result, ChuanLaneInfo::class.java)
                        if (bean?.getaMapLaneInfo() != null) {
                            if (AppManager.currentActivity()!!.localClassName == "view.map.MapGuideActivity") {
                                Log.i(
                                    "yjj",
                                    "refresh map lane info view" + AppManager.currentActivity()!!.localClassName
                                )
                                MapGuideActivity.refreshLaneInfoView(bean.getaMapLaneInfo())
                            } else {
                                Log.i("yjj", "goto map lane info view")
                                var intent = Intent(AppManager.currentActivity(), MapGuideActivity::class.java)
                                intent.putExtra("laneInfoData", bean.getaMapLaneInfo())
                                startActivity(intent)
                            }

                        }
                    }

                }


                //地图规划
                Constants.COMMON_TYPE_GD_MAP_PLAN -> {
                    //if (!getSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, false)) {
                    var bean = JSON.parseObject(result, ChuanGDPlanBean::class.java)
                    if (bean != null) {
                        Log.i("yjj", "goto map guide predict view")
                        var intent = Intent(AppManager.currentActivity(), GdMapPreviewActivity::class.java)
                        intent.putExtra("data", bean)
                        startActivity(intent)
                    }
                    //}
                }

                //手机端退出导航
                Constants.COMMON_TYPE_FINISH_MAP -> {
                    var bean = JSON.parseObject(result, SwitchMsgBean::class.java)
                    if (bean != null) {
                        Log.i("yjj", "msg >>> phone finish map")
                        if (AppManager.currentActivity()!!.localClassName == "view.map.MapGuideActivity") {
                            AppManager.currentActivity()!!.finish()
                            putSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, false)
                            mDelayMills = 1 * 1000
                            shortToast("导航已退出")
                        }

                    }
                }

                Constants.COMMON_TYPE_NOTIFICATION -> {

                    LogUtil.e(
                        "yjj", "receive from phone to get notification time"
                                + "seconds = " + getSp("SP_KEY_NOTIFICATION_TIME", 3)
                                + ", bean.isOn = " + getSp("SP_KEY_NOTIFICATION_SWITCH", "off")
                    )
                    if (getSp("SP_KEY_NOTIFICATION_SWITCH", "off") == "on") {
                        var bean = JSON.parseObject(result, NotificationBean::class.java)
                        if (bean != null) {
                            //判断手机屏幕是否亮着
                            var intent = Intent(AppManager.currentActivity(), DialogActivity::class.java)
                            intent.putExtra("data", bean)
                            startActivity(intent)
                        }
                    }
                }

                Constants.COMMON_TYPE_TRANS_PHOTO -> {

                    var bean = JSON.parseObject(result, WifiPhotoBean::class.java)
                    if (bean != null) {
                        TransferPhotosManager.getNewInstance().handleEvent(MessageEvent(bean.btntype, bean.ip))
                        //EventBus.getDefault().postSticky(MessageEvent(bean.btntype, bean.ip))
                    }
                }

                Constants.COMMON_TYPE_CONNECT_WIFI -> {

                    var bean = JSON.parseObject(result, WifiLinkBean::class.java)
                    if (bean != null) {
                        //EventBus.getDefault().postSticky(bean)
                        //WifiConnectManager.getNewInstance().handleMsg(bean)

                        if (bean.btntype == "搜索") {
                            if (ConnectWifTools.getNewInstance().switchWifiStatus) {
                                ConnectWifTools.getNewInstance().scanWifi()
                            } else {
                                sendOpenWifiToPhone()
                            }

                        } else if (bean.btntype == "连接wifi") {
                            ConnectWifTools.getNewInstance().connect(bean)
                        } else if (bean.btntype == "关闭") {
                            ConnectWifTools.getNewInstance().changeWifiStatus(false)
                        } else if (bean.btntype == "打开 ") {
                            ConnectWifTools.getNewInstance().changeWifiStatus(true)
                        }

                        ConnectWifTools.getNewInstance().setOnNetWorkStateChangeListener {
                            Log.i("yjj", "refresh wifi status >>>>" + it)
                            (mSysFragment as SysInfoFragment).refreshWifiStatus(it)
                        }

                    }

                }

                Constants.COMMON_TYPE_SWITCH -> {
                    var bean = JSON.parseObject(result, SwitchBean::class.java)
                    if (bean != null) {
                        EventBus.getDefault().postSticky(bean)
                    }

                }

                //todo 收到手机端返回的旅游景点信息
                Constants.COMMON_TYPE_SCENE_DATA -> {
                    var bean = JSON.parseObject(result, ChuanSceneBean::class.java)
                    if (bean != null && bean.scenceBeans != null) {
                        //EventBus.getDefault().postSticky(bean)

                        if (bean.scenceBeans.size >= 0) {
                            Log.i("yjj", "scene size = " + bean.scenceBeans.size)
                            if (AppManager.currentActivity()!!.localClassName == "view.travel.TravelActivity") {
                                Log.i("yjj", "refresh map view" + AppManager.currentActivity()!!.localClassName)
                                TravelActivity.refreshView(bean)
                            } else {
                                var intent = Intent(this, TravelActivity::class.java)
                                intent.putExtra("data", bean)
                                startActivity(intent)
                                LogUtil.e("yjj", "receive from phone to get sceneList")

                            }
                        }

                    }

                }

                //todo 收到手机端设置的翻译初始语言和目标语言
                Constants.COMMON_TYPE_TRANSLATE_LANGUAGE -> {
                    var bean = JSON.parseObject(result, ChuanTranslateBean::class.java)
                    if (bean != null) {
                        LogUtil.e(
                            "yjj", "receive from phone to get language type"
                                    + "origin," + bean.yuanCode
                                    + "target," + bean.mubiaoCode
                                    + "origin chinese name," + bean.yuanCna
                                    + "target chinese name," + bean.mubiaoCna
                        )
                        putSp<String>("SP_KEY_ORIGIN_LANGUAGE", bean.yuanCode)
                        putSp<String>("SP_KEY_TARGET_LANGUAGE", bean.mubiaoCode)
                        putSp<String>("SP_KEY_ORIGIN_LANGUAGE_CNA", bean.yuanCna)
                        putSp<String>("SP_KEY_TARGET_LANGUAGE_CNA", bean.mubiaoCna)
                    }
                }

                Constants.COMMON_TYPE_SHOW_NOTIFICATION_TIME -> {
                    var bean = JSON.parseObject(result, ChuanNotiTimes::class.java)
                    if (bean != null) {
                        LogUtil.e(
                            "yjj", "receive from phone to get notification time"
                                    + "seconds = " + bean.seconds
                                    + ", bean.isOn = " + bean.isOn
                        )
                        putSp<Int>("SP_KEY_NOTIFICATION_TIME", bean.seconds)
                        putSp<String>("SP_KEY_NOTIFICATION_SWITCH", bean.isOn)
                    }
                }

                Constants.COMMON_TYPE_SHOW_SCENE_TYPE -> {
                    var bean = JSON.parseObject(result, SceneInfoTypeBean::class.java)
                    if (bean != null) {
                        LogUtil.e("yjj", "receive from phone to get scene type" + bean.infoType)
                        putSp<String>(Constants.SP_KEY_TRAVEL_GUIDE_TYPE, bean.infoType)
                    }
                }


                Constants.COMMON_TYPE_SLEEP_SCREEN_TIME -> {
                    var bean = JSON.parseObject(result, ChuanNotiTimes::class.java)
                    if (bean != null) {
                        LogUtil.e("yjj", "receive from phone : sleep time =" + bean.seconds)
                        putSp(Constants.SP_KEY_COMMON_SLEEP_SCREEN_TIME, bean.seconds)
                    }
                }

                //todo 接受手机端设置HDR模式 SP_KEY_CAMERA_SCENE_MODE


                Constants.COMMON_TYPE_CALL_PHONE_TYPE -> {
                    var bean = JSON.parseObject(result, PhoneBean::class.java)
                    if (bean != null) {
                        //onCallHangUp onCalling onCallRinging
                        LogUtil.e("yjj", "call phone ~~~~~~~~~~" + bean.phoneType)

                        /*方式一*/

                        if (bean.phoneType == "onCallRinging") {
                            var intent = Intent(this, BluetoothCallActivity::class.java)

                            //var intent = Intent(this, PhoneCallActivity::class.java)
                            if (bean.name != null) {
                                intent.putExtra("contactName", bean.name)
                            }

                            if (bean.number != null) {
                                intent.putExtra("contactPhoneNumber", bean.number)
                            }
                            startActivity(intent)
                        } else if (bean.phoneType == "onCallHangUp") {
                            if (AppManager.currentActivity()!!.localClassName == "view.phonecall.BluetoothCallActivity") {
                                AppManager.currentActivity()!!.finish()
                            }

                        }


                        /* 方式二*/

                        /*              if (bean.phoneType != null) {

                                          var callType: PhoneCallService.CallType? = null

                                          if (bean.phoneType == "CALL_IN") {
                                              callType = PhoneCallService.CallType.CALL_IN
                                          } else if (bean.phoneType == "CALL_OUT") {
                                              callType = PhoneCallService.CallType.CALL_OUT
                                          }

                                          PhoneCallActivity.actionStart(this, bean.number, callType)
                                      }*/

                    }
                }

            }

        } catch (e: JSONException) {
            Toast.makeText(this, "operateResult JSON 解析错误", Toast.LENGTH_SHORT)
            LogUtil.e("yjj", e.toString())
        }


    }

    private fun sendOpenWifiToPhone() {
        var data = WifiConnectFailedBean()
        data.type = "gotoOpenWifi"
        LogUtil.e("yjj", "sendOpenWifiToPhone ~~~~~")
        val dataStr = JSON.toJSONString(data)
        CommunicateToPhoneHelper.instance.write(dataStr)
    }


    private fun initViewpager() {
        mViewPagerAdapter = HomePagerAdapter(supportFragmentManager)

        //var menuFragment = SysInfoFragment()
        mSysFragment = SysInfoFragment()
        mViewPagerAdapter!!.addFragment(mSysFragment, "")

        var menuFragment1 = MenuFragment()
        menuFragment1.setViews("拍照", R.drawable.icon_main_function_camera)
        mViewPagerAdapter!!.addFragment(menuFragment1, "")

   /*     var menuFragment2 = MenuFragment()
        menuFragment2.setViews("翻译", R.drawable.icon_main_function_translate)
        mViewPagerAdapter!!.addFragment(menuFragment2, "")*/

        var menuFragment3 = MenuFragment()
        menuFragment3.setViews("指南针", R.drawable.icon_main_function_travel)
        mViewPagerAdapter!!.addFragment(menuFragment3, "")

        var menuFragment4 = MenuFragment()
        menuFragment4.setViews("视频", R.drawable.icon_main_function_travel)
        mViewPagerAdapter!!.addFragment(menuFragment4, "")

        var menuFragment5 = MenuFragment()
        menuFragment5.setViews("wifi", R.drawable.icon_main_function_setting)
        mViewPagerAdapter!!.addFragment(menuFragment5, "")
        var menuFragment6 = MenuFragment()
        menuFragment6.setViews("音量", R.drawable.icon_main_function_setting)
        mViewPagerAdapter!!.addFragment(menuFragment6, "")
        var menuFragment7 = MenuFragment()
        menuFragment7.setViews("亮度", R.drawable.icon_main_function_setting)
        mViewPagerAdapter!!.addFragment(menuFragment7, "")
        var menuFragment8 = MenuFragment()
        menuFragment8.setViews("录音播放", R.drawable.icon_main_function_setting)
        mViewPagerAdapter!!.addFragment(menuFragment8, "")

        vp_main_pager.adapter = mViewPagerAdapter
        vp_main_pager.currentItem = 0
        vp_main_pager!!.setPageTransformer(false, ZoomOutPageTransformer())
        vp_main_pager!!.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(p0: Int) {
            }

            override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
            }

            override fun onPageSelected(position: Int) {

                //处理position。让position落在[0,fragmentList.size)中，防止数组越界
                var realPos = position % mViewPagerAdapter!!.size

                Log.i("yjj", "onPageSelected$position, >>>> realPos = $realPos")
                mCurPos = realPos
                if (mCurPos == 0) {
                    setBleConnectStatusUI()
                    setWifiConnectStatusUI()
                }


            }

        })


    }


    override fun onBackPressed() {
        super.onBackPressed()
        Log.i("yjj", "onBackPressed~~~")
        return

    }


    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {

        Log.i("yjj", "onKeyUp >>>keyCode" + keyCode + ", action =" + event!!.action)

        when (keyCode) {

            119 -> {
                Log.i("yjj", "Fn按键对应键值为119")
                Toast.makeText(this@HomeGuideActivity, "功能按键测试完毕", Toast.LENGTH_LONG).show()
            }
            141 -> {
                Log.i("yjj", "触控长按按下对应键值为141")
            }

            142 -> {
                Log.i("yjj", "触控长按松开对应键值为142")
            }

            //首页禁止退出到系统页面
            4 -> {
                return true
                Log.i("yjj", "触控长按 双击返回 4")
            }
        }

        return super.onKeyUp(keyCode, event)
    }


    override fun onKeyLongPress(keyCode: Int, event: KeyEvent?): Boolean {

        Log.i("yjj", "onKeyLongPress >>>keyCode" + keyCode + ", action =" + event!!.action)

        return super.onKeyLongPress(keyCode, event)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        Log.i("yjj", "onKeyDown >>>keyCode" + keyCode + ", action =" + event!!.action)
        if (keyCode == 66) {
            gotoDetail()
        }

        return super.onKeyDown(keyCode, event)
    }

    private fun gotoDetail() {
        when (mCurPos) {
            0 -> {
                BleManager.getInstance().enableDiscoverable(300)
                //BlueToothUtils.setDiscoverableTimeout(300)
            }

            1 -> {
                startVideoRecordActivity()
            }

      /*      2 -> {
                startActivity(Intent(this, TranslateLanguageActivity::class.java))
            }
*/
            2 -> {
                startActivity(Intent(this, TestMiCompassActivity::class.java))
            }

            3 -> {
                startActivity(Intent(this, VideoActivity::class.java))
            }

            4 -> {
                startActivity(Intent(this, MainActivity::class.java))
            }
            5 -> {
                startActivity(Intent(this, VolumeActivity::class.java))
            }
            6 -> {
                startActivity(Intent(this, BrightnessActivity::class.java))
            }
            7 -> {
                startActivity(Intent(this, RadioActivity::class.java))
            }

        }
    }


    private fun startVideoRecordActivity() {
        SurfaceCameraActivity.startActivity(mContext, SurfaceCameraActivity.SCENE_MODE)
    }


    override fun onDestroy() {
        super.onDestroy()
        Log.i("yjj", "onDestroy")
        TransferPhotosManager.getNewInstance().unregisterAndStop()
        CompassManager.getNewInstance().unregister()
        SugonGlassesInfoManager.instance.unRegister()
    }


}


